class RandomizedSet {

    List<Integer> nums;
    Map<Integer,Integer> map;
    Random random;
    /** Initialize your data structure here. */
    public RandomizedSet() {
        nums = new ArrayList<Integer>();
        map = new HashMap<>();
        random = new Random();
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        if(map.containsKey(val)) {
            return false;
        }
        int length = nums.size();
        nums.add(val);
        map.put(val,length);
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        if(!map.containsKey(val)) {
            return false;
        }
        int index = map.get(val);//取得链表中的下标
        int last = nums.get(nums.size() - 1);//获取到最后的元素
        nums.set(index,last);//设置这个下标的元素为last
        map.put(last,index);//更新Map中index该下标的值为last
        nums.remove(nums.size() - 1);//删除链表中的最后一个元素
        map.remove(val);//移除Map中的该元素
        return true;
    }
    
    /** Get a random element from the set. */
    public int getRandom() {
        int randomIndex = random.nextInt(nums.size());
        return nums.get(randomIndex);
    }
}

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */